<template>
  <div class="customs-trade-info-container">
    <!-- 使用封装的顶部导航组件 -->
    <MainHeader />
    
    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 使用封装的侧边菜单组件 -->
      <SideMenu />
      
      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 基本搜索区域 -->
        <div class="search-module">
          <div class="search-module-title">{{ t('customs.search') }}</div>
          <div class="search-area">
            <div class="search-column">
              <div class="search-field">
                <el-input
                  v-model="queryParams.product_keyword_english"
                  :placeholder="t('customs.product.keyword.english')"
                  clearable
                  @input="debounceSearch"
                  @clear="fetchTradeInfos"
                />
              </div>
            </div>
            
            <div class="search-field">
              <el-input
                v-model="queryParams.hs_code"
                :placeholder="t('customs.hs.code')"
                clearable
                @input="debounceSearch"
                @clear="fetchTradeInfos"
              />
            </div>
          </div>
          
          <!-- 重置搜索按钮 -->
          <div class="reset-search">
            <el-button @click="resetAllSearch" type="primary" plain>{{ t('customs.reset.search') }}</el-button>
          </div>
        </div>
        
        <!-- 主内容区域 - 数据展示 -->
        <div class="trade-info-main">
          <!-- 导出数据模块 -->
          <div class="export-module">
            <el-button @click="exportData" class="export-module-btn" type="primary" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              {{ t('customs.export.data') }}
            </el-button>
          </div>
          
          <!-- 数据列表显示 -->
          <div class="data-list-container">
            <div v-if="loading" class="data-loading">
              <el-skeleton :rows="5" animated />
            </div>
            
            <template v-else>
              <div v-if="tradeInfos.length === 0" class="no-data">
                {{ t('customs.no.data') }}
              </div>
              <div v-else>
                <div v-for="(item, index) in tradeInfos" :key="item.id || index" class="info-card">
                  <!-- 数据头部概览 -->
                  <div class="info-card-header">
                    <div class="info-card-title">
                      <span>{{ item.productKeywordEnglish }}</span>
                      <span class="info-card-subtitle">{{ item.hsCode }} | {{ item.billOfLadingNumber }}</span>
                    </div>
                    <div class="info-card-amount">${{ item.totalAmount }} ({{ item.quantity }}件)</div>
                  </div>
                  <!-- 详细数据展示 -->
                  <div class="info-card-content">
                    <div class="info-item">
                      <span class="info-label">{{ t('customs.product.keyword') }}</span>
                      <span class="info-value">{{ item.productKeywordEnglish }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">{{ t('customs.hs.code') }}</span>
                      <span class="info-value">{{ item.hsCode }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">{{ t('customs.bill.of.lading.number') }}</span>
                      <span class="info-label">提单号:</span>
                      <span class="info-value">{{ item.billOfLadingNumber }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">产品描述:</span>
                      <span class="info-value">{{ item.productDescription }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">原产国:</span>
                      <span class="info-value">{{ item.originCountry }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">供应商:</span>
                      <span class="info-value">{{ item.supplierEnglish }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">起运港:</span>
                      <span class="info-value">{{ item.portOfLoading }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">目的国:</span>
                      <span class="info-value">{{ item.destinationCountry }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">采购商:</span>
                      <span class="info-value">{{ item.purchaserEnglish }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">目的港:</span>
                      <span class="info-value">{{ item.portOfDestination }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">开始日期:</span>
                      <span class="info-value">{{ item.startDate }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">结束日期:</span>
                      <span class="info-value">{{ item.endDate }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
          
          <!-- 恢复分页 -->
          <div class="pagination-container">
            <el-pagination
              :current-page="pagination.currentPage"
              :page-size="pagination.pageSize"
              :total="pagination.totalItems"
              layout="total, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 导出对话框 -->
  <el-dialog
    v-model="exportDialogVisible"
    title="导出数据"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="export-dialog-content">
      <div class="export-info">
        <p>符合条件的记录数: <span class="export-highlight">{{ totalMatchCount }}</span></p>
        <p>当前导出余额: <span class="export-highlight">{{ userBalance.exportQuotaRemaining }}</span></p>
        <p class="export-note">注意: 每导出一条记录将消耗一点导出额度</p>
      </div>
      
      <div class="export-input">
        <p>请输入要导出的记录数:</p>
        <el-input-number
          v-model="exportCount"
          :min="1"
          :max="Math.max(1, Math.min(totalMatchCount, 1000000, userBalance.exportQuotaRemaining || 1))"
          :step="100"
          size="large"
          controls-position="right"
        />
        
        <div class="export-warnings">
          <p v-if="isExportCountExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            导出数量不能超过符合条件的记录数
          </p>
          <p v-if="isBalanceInsufficient" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            导出余额不足
          </p>
          <p v-if="isExportLimitExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            导出数量不能超过100万
          </p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="doExport" 
          :loading="exportLoading"
          :disabled="isExportCountExceeded || isBalanceInsufficient || isExportLimitExceeded || !exportCount"
        >
          确认导出
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import request from '@/utils/request';
import MainHeader from '@/components/MainHeader.vue';
import SideMenu from '@/components/SideMenu.vue';
import { Download } from '@element-plus/icons-vue';
import { ElMessage, ElInput, ElInputNumber } from 'element-plus';
import { getCustomsTradeList, getProductKeywords, getHsCodes, exportCustomsTradeInfo, getCustomsTradeCount, getUserBalanceInfo } from '@/api/customs';
import { t } from '@/utils/i18n';

export default {
  name: 'CustomsTradeInfo',
  components: {
    MainHeader,
    SideMenu,
    Download
  },
  setup() {
    const queryParams = reactive({
      product_keyword_english: '',
      hs_code: ''
    });
    
    const advancedQueryParams = reactive({
      bill_of_lading_number: '',
      origin_country: '',
      supplier_english: '',
      port_of_loading: '',
      destination_country: '',
      purchaser_english: '',
      port_of_destination: '',
      product_description: ''
    });
    
    const loading = ref(false);
    const exportLoading = ref(false);
    
    const tradeInfos = ref([]);
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      totalItems: 0
    });
    
    const startDate = ref('');
    const endDate = ref('');
    
    // 防抖搜索
    const searchTimer = ref(null);
    const debounceSearch = () => {
      if (searchTimer.value) {
        clearTimeout(searchTimer.value);
      }
      searchTimer.value = setTimeout(() => {
        fetchTradeInfos();
      }, 300);
    };
    
    // 获取海关贸易数据
    const fetchTradeInfos = async () => {
      loading.value = true;
      try {
        const requestParams = {
          productKeywordEnglish: queryParams.product_keyword_english || null,
          hsCode: queryParams.hs_code || null,
          billOfLadingNumber: advancedQueryParams.bill_of_lading_number || null,
          originCountry: advancedQueryParams.origin_country || null,
          supplierEnglish: advancedQueryParams.supplier_english || null,
          portOfLoading: advancedQueryParams.port_of_loading || null,
          destinationCountry: advancedQueryParams.destination_country || null,
          purchaserEnglish: advancedQueryParams.purchaser_english || null,
          portOfDestination: advancedQueryParams.port_of_destination || null,
          productDescription: advancedQueryParams.product_description || null,
          startDate: startDate.value || null,
          endDate: endDate.value || null,
          page: pagination.currentPage,
          size: pagination.pageSize
        };
        
        const response = await getCustomsTradeList(requestParams);
        // 检查响应状态码
        if (response.code === 200) {
          // 直接使用返回的数据
          const responseData = response.data;
          if (responseData && Array.isArray(responseData.records)) {
            tradeInfos.value = responseData.records;
            pagination.totalItems = responseData.total || 0;
            pagination.pageSize = responseData.size || 10;
            if (responseData.records.length === 0) {
              ElMessage.warning('暂无数据');
            }
          } else {
            // console.error('Records is not an array:', responseData);
            tradeInfos.value = [];
            pagination.totalItems = 0;
            ElMessage.warning('暂无数据');
          }
        } else {
          // console.error('API Error:', response.msg);
          ElMessage.error(response.msg || '获取数据失败');
          tradeInfos.value = [];
          pagination.totalItems = 0;
        }
      } catch (error) {
        // console.error('Request Error:', error);
        ElMessage.error(`获取数据失败: ${error.message || '未知错误'}`);
        tradeInfos.value = [];
        pagination.totalItems = 0;
      } finally {
        loading.value = false;
      }
    };
    
    // 导出数据
    const exportData = async () => {
      exportLoading.value = true;
      try {
        // 先获取符合条件的记录数量
        await fetchExportCount();
        
        // 再获取用户余额
        await fetchUserBalance();
        
        // 显示导出对话框
        exportDialogVisible.value = true;
      } catch (error) {
        console.error('准备导出失败:', error);
        ElMessage.error('准备导出失败，请稍后重试');
      } finally {
        exportLoading.value = false;
      }
    };
    
    // 重置高级搜索
    const resetAdvancedSearch = () => {
      Object.keys(advancedQueryParams).forEach(key => {
        advancedQueryParams[key] = '';
      });
      startDate.value = '';
      endDate.value = '';
      debounceSearch();
    };
    
    // 重置所有搜索条件
    const resetAllSearch = () => {
      queryParams.product_keyword_english = '';
      queryParams.hs_code = '';
      resetAdvancedSearch();
    };
    
    // 处理日期变化
    const handleDateChange = () => {
      debounceSearch();
    };
    
    // 处理分页大小变化
    const handleSizeChange = (val) => {
      pagination.pageSize = val;
      fetchTradeInfos();
    };
    
    // 处理当前页变化
    const handleCurrentChange = (val) => {
      pagination.currentPage = val;
      fetchTradeInfos();
    };
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchTradeInfos();
    });
    
    const productKeywords = ref([]);
    const hsCodes = ref([]);
    const originCountries = ref([]);
    const destinationCountries = ref([]);
    const loadingPorts = ref([]);
    const destinationPorts = ref([]);
    
    // 导出相关的状态
    const exportDialogVisible = ref(false);
    const totalMatchCount = ref(0);
    const exportCount = ref(0);
    const userBalance = ref({
      exportQuotaRemaining: 0
    });
    const isExportCountExceeded = computed(() => {
      return exportCount.value > totalMatchCount.value;
    });
    const isBalanceInsufficient = computed(() => {
      return exportCount.value > userBalance.value.exportQuotaRemaining;
    });
    const isExportLimitExceeded = computed(() => {
      return exportCount.value > 1000000;
    });
    
    // 获取符合条件的记录数量
    const fetchExportCount = async () => {
      try {
        const params = {
          productKeywordEnglish: queryParams.product_keyword_english || null,
          hsCode: queryParams.hs_code || null,
          billOfLadingNumber: advancedQueryParams.bill_of_lading_number || null,
          originCountry: advancedQueryParams.origin_country || null,
          supplierEnglish: advancedQueryParams.supplier_english || null,
          portOfLoading: advancedQueryParams.port_of_loading || null,
          destinationCountry: advancedQueryParams.destination_country || null,
          purchaserEnglish: advancedQueryParams.purchaser_english || null,
          portOfDestination: advancedQueryParams.port_of_destination || null,
          productDescription: advancedQueryParams.product_description || null,
          startDate: startDate.value || null,
          endDate: endDate.value || null
        };
        
        const response = await getCustomsTradeCount(params);
        
        if (response.code === 200) {
          // 从响应中提取count字段
          const count = response.data.count || 0;
          
          totalMatchCount.value = count > 1000000 ? 1000000 : count;
          exportCount.value = Math.min(totalMatchCount.value, 1000); // 默认设置为1000条或总数
          return count;
        } else {
          ElMessage.error(response.msg || '获取记录数量失败');
          return 0;
        }
      } catch (error) {
        console.error('获取记录数量失败:', error);
        ElMessage.error('获取记录数量失败，请稍后重试');
        return 0;
      }
    };
    
    // 获取用户余额
    const fetchUserBalance = async () => {
      try {
        const response = await getUserBalanceInfo();
        if (response.code === 200 && response.data) {
          userBalance.value = response.data;
          return response.data;
        } else {
          console.error('获取余额信息异常:', response);
          ElMessage.error(response.msg || '获取余额信息失败');
          return { exportQuotaRemaining: 0 };
        }
      } catch (error) {
        console.error('获取余额信息失败:', error);
        ElMessage.error('获取余额信息失败，请稍后重试');
        return { exportQuotaRemaining: 0 };
      }
    };
    
    // 执行导出操作
    const doExport = async () => {
      // 检查导出数量
      if (isExportCountExceeded.value) {
        ElMessage.error(`导出数量不能超过符合条件的记录数 ${totalMatchCount.value}`);
        return;
      }
      
      // 检查导出上限
      if (isExportLimitExceeded.value) {
        ElMessage.error('导出数量不能超过100万');
        return;
      }
      
      // 检查余额
      if (isBalanceInsufficient.value) {
        ElMessage.error(`导出余额不足，当前余额: ${userBalance.value.exportQuotaRemaining}`);
        return;
      }
      
      // 确保导出数量是有效的数字
      if (!exportCount.value || isNaN(Number(exportCount.value)) || Number(exportCount.value) <= 0) {
        ElMessage.error('请输入有效的导出数量');
        return;
      }
      
      exportLoading.value = true;
      try {
        // 准备导出参数对象
        const exportParams = {
          productKeywordEnglish: queryParams.product_keyword_english || null,
          hsCode: queryParams.hs_code || null,
          billOfLadingNumber: advancedQueryParams.bill_of_lading_number || null,
          originCountry: advancedQueryParams.origin_country || null,
          supplierEnglish: advancedQueryParams.supplier_english || null,
          portOfLoading: advancedQueryParams.port_of_loading || null,
          destinationCountry: advancedQueryParams.destination_country || null,
          purchaserEnglish: advancedQueryParams.purchaser_english || null,
          portOfDestination: advancedQueryParams.port_of_destination || null,
          productDescription: advancedQueryParams.product_description || null,
          startDate: startDate.value || null,
          endDate: endDate.value || null,
          exportCount: Number(exportCount.value) // 添加导出数量参数
        };
        ElMessage.info('正在准备导出数据，请稍候...');
        
        // 发送请求
        const response = await exportCustomsTradeInfo(exportParams);
        
        // 检查响应是否为blob
        if (!response || !response.data) {
          console.error('导出失败：没有响应数据', response);
          throw new Error('导出失败：服务器未返回数据');
        }
        
        if (!(response.data instanceof Blob)) {
          console.error('导出失败：响应不是Blob类型', response);
          throw new Error('导出失败：服务器返回格式不正确');
        }
        
        // 获取Content-Type，如果没有则使用默认值
        const contentType = response.headers && response.headers['content-type'] 
          ? response.headers['content-type'] 
          : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        
        // 检查是否是错误响应
        if (contentType.includes('json')) {
          // 可能是错误响应，尝试解析
          const reader = new FileReader();
          
          // 使用Promise包装FileReader
          const readJsonResponse = new Promise((resolve, reject) => {
            reader.onload = function() {
              try {
                const result = reader.result;
                const errorResponse = JSON.parse(result);
                console.error('导出失败：', errorResponse);
                resolve(errorResponse);
              } catch (e) {
                console.error('无法解析错误响应:', e);
                reject(new Error('导出失败：无法识别的错误'));
              }
            };
            reader.onerror = function(e) {
              console.error('读取JSON响应失败:', e);
              reject(new Error('导出失败：无法读取错误响应'));
            };
          });
          
          reader.readAsText(response.data);
          
          try {
            const errorData = await readJsonResponse;
            // 显示具体的错误信息
            const errorMessage = errorData.msg || errorData.message || '未知错误';
            ElMessage.error(`导出失败：${errorMessage}`);
            console.error('导出错误详情:', errorData);
            
            // 如果错误与参数相关，可能需要提示用户修改导出数量
            if (errorMessage.includes('exportCount') || errorMessage.includes('导出数量')) {
              ElMessage.warning('请检查导出数量是否正确设置');
            }
            
            return;
          } catch (e) {
            ElMessage.error(e.message || '导出失败：无法识别的错误');
            return;
          }
        }
        
        // 创建Blob对象
        const blob = new Blob([response.data], { type: contentType });
        
        // 获取文件名
        let fileName = '海关贸易数据.xlsx';
        const disposition = response.headers && response.headers['content-disposition'];
        if (disposition && disposition.includes('filename=')) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) {
            fileName = matches[1].replace(/['"]/g, '');
            try {
              fileName = decodeURIComponent(fileName);
            } catch (e) {
              console.warn('文件名解码失败:', e);
            }
          }
        }
        
        // 下载文件
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        
        // 关闭导出对话框
        exportDialogVisible.value = false;
        
        // 更新用户余额
        await fetchUserBalance();
        
        ElMessage.success('数据导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error(`导出失败: ${error.message || '未知错误'}`);
      } finally {
        exportLoading.value = false;
      }
    };
    
    return {
      queryParams,
      advancedQueryParams,
      loading,
      exportLoading,
      tradeInfos,
      pagination,
      startDate,
      endDate,
      productKeywords,
      hsCodes,
      originCountries,
      destinationCountries,
      loadingPorts,
      destinationPorts,
      fetchTradeInfos,
      exportData,
      resetAllSearch,
      handleCurrentChange,
      handleSizeChange,
      handleDateChange,
      fetchExportCount,
      fetchUserBalance,
      doExport,
      exportDialogVisible,
      totalMatchCount,
      exportCount,
      userBalance,
      isExportCountExceeded,
      isBalanceInsufficient,
      isExportLimitExceeded,
      t
    };
  }
};
</script>

<style scoped>
.customs-trade-info-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.main-container {
  display: flex;
  width: 100%;
  min-height: calc(100vh - 60px);
  position: relative;
  overflow: hidden;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 60px);
}

.search-module {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.search-module-title {
  text-align: center;
  font-size: 18px;
  font-weight: 700;
  color: #333;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  gap: 40px;
  padding: 0 5%;
}

.search-column {
  flex: 1;
  max-width: 450px;
}

.search-field {
  flex: 1;
  max-width: 450px;
  margin-bottom: 10px;
}

.search-field .el-input__inner {
  height: 50px;
  line-height: 50px;
  font-size: 15px;
  border-radius: 4px;
  border-width: 2px;
}

.trade-info-main {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.export-module {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.data-list-container {
  width: 100%;
}

.info-card {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 15px;
  margin-bottom: 15px;
}

.info-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.info-card-title {
  display: flex;
  flex-direction: column;
}

.info-card-title span:first-child {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.info-card-subtitle {
  font-size: 13px;
  color: #909399;
  margin-top: 5px;
}

.info-card-amount {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.info-card-content {
  display: flex;
  flex-wrap: wrap;
}

.info-item {
  line-height: 28px;
  font-size: 14px;
  display: flex;
  width: 50%;
}

.info-label {
  color: #666;
  min-width: 80px;
  display: inline-block;
}

.info-value {
  color: #333;
  font-weight: 500;
}

.data-loading {
  padding: 20px;
}

.no-data {
  padding: 30px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 隐藏旧版搜索表单和搜索按钮 */
.search-form, .search-btn, .search-label {
  display: none;
}

.reset-search {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

/* 确保所有按钮样式统一 */
.reset-search .el-button {
  min-width: 120px;
  height: 36px;
  font-size: 14px;
  border-radius: 4px;
}

/* 导出对话框样式 */
.export-dialog-content {
  padding: 10px 0;
}

.export-info {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.export-highlight {
  font-weight: bold;
  color: #409eff;
  margin: 0 5px;
}

.export-input {
  margin-bottom: 15px;
}

.export-input p {
  margin-bottom: 10px;
}

.export-warnings {
  margin-top: 15px;
}

.export-warning {
  color: #f56c6c;
  font-size: 13px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.export-warning i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.export-note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>